import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css' // 新增样式导入
import router from '@/router'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: 'https://big-event-vue-api-t.itheima.net/',
  // 超时
  timeout: 10000,
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const useUserStores = useUserStore()
    if (useUserStores.token) {
      config.headers['Authorization'] = useUserStores.token
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    console.log(res.data)
    if (res.data.code === 0) {
      return res
    }
    ElMessage.error(res.data.message || 'Error')
    return Promise.reject(res.data)
  },
  (error) => {
    if (error.response?.status === 401) {
      router.push('/login')
    }
    ElMessage.error(res.response.data.message || 'Error')
    return Promise.reject(error)
  },
)

export default service
